package workflow

import (
	"xagent/internal/messages"
	proto "xagent/proto/v1"
)

// TaskAdapter converts between proto.Task and messages.Message
type TaskAdapter struct {
	task *proto.Task
}

// NewTaskAdapter creates a new task adapter
func NewTaskAdapter(task *proto.Task) *TaskAdapter {
	return &TaskAdapter{task: task}
}

// GetType implements messages.Message interface
func (t *TaskAdapter) GetType() messages.MessageType {
	return messages.MessageType(t.task.Name)
}

// GetContent implements messages.Message interface
func (t *TaskAdapter) GetContent() string {
	return t.task.Description
}

// GetAction implements messages.Message interface
func (t *TaskAdapter) GetAction() string {
	if t.task.Metadata != nil {
		if action, ok := t.task.Metadata["action"]; ok {
			return action
		}
	}
	return ""
}

// GetRole implements messages.Message interface
func (t *TaskAdapter) GetRole() string {
	if t.task.Metadata != nil {
		if role, ok := t.task.Metadata["role"]; ok {
			return role
		}
	}
	return ""
}

// GetMetadata returns the task metadata
func (t *TaskAdapter) GetMetadata() map[string]string {
	return t.task.Metadata
}

// ToProtoMessage converts a messages.Message to proto.AgentMessage
func ToProtoMessage(msg messages.Message) *proto.AgentMessage {
	return &proto.AgentMessage{
		Type: proto.MessageType_MESSAGE_TYPE_RESPONSE,
		Content: &proto.AgentMessage_Message{
			Message: msg.GetContent(),
		},
		Metadata: make(map[string]string),
	}
}

// IsErrorMessage checks if a message is an error message
func IsErrorMessage(msg messages.Message) bool {
	return msg.GetType() == messages.TypeError
}

// GetErrorContent extracts error content from a message
func GetErrorContent(msg messages.Message) string {
	if IsErrorMessage(msg) {
		return msg.GetContent()
	}
	return ""
}

// GetMessageContent extracts regular content from a message
func GetMessageContent(msg messages.Message) string {
	if !IsErrorMessage(msg) {
		return msg.GetContent()
	}
	return ""
}
